package panda.li.navigation.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * Gson识别转化
 */
public class JsonUtil {
    private static Gson gson;

    private JsonUtil() {
    }

    private static Gson getGson() {
        if (gson == null) {
            synchronized (JsonUtil.class) {
                if (gson == null) {
                    GsonBuilder builder = new GsonBuilder()
                            .setDateFormat("yyyy-MM-dd HH:mm:ss")   //日期格式转换
                            ;
//                    JsonDeserializer deserializer = (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong());
//                    builder.registerTypeAdapter(Date.class, deserializer);
                    gson = builder.create();
                }
            }
        }
        return gson;
    }

    public static <T> String toJson(T object) {
        return getGson().toJson(object);
    }


    public static <T> T fromJson(String json, Type type) {
        return getGson().fromJson(json, type);
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        return getGson().fromJson(json, clazz);
    }

    public static <T> T fromJson(JsonElement json, Class<T> clazz) {
        return getGson().fromJson(json, clazz);
    }
}
